package com.gxuwz.stats.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gxuwz.stats.entity.DecisionConsulting;
import com.gxuwz.stats.entity.IntellectualProperty;
import com.gxuwz.stats.entity.User;
import com.gxuwz.stats.security.jwt.JwtTokenUtil;
import com.gxuwz.stats.service.IntellectualPropertyService;
import com.gxuwz.stats.service.UserService;
import com.gxuwz.stats.utils.ExcelExportUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/userIntellectualPro")
public class IntellectualProUserController {
    @Autowired
    private IntellectualPropertyService intellectualPropertyService;
    @Autowired
    private UserService userService;

    /**
     * 分页查询
     * @param params
     * @param currentPage
     * @param pageSize
     * @return
     */
    @GetMapping("/getUserIntelProList")
    public ResponseEntity<Map<String, Object>> getUserIntelProList(
            @RequestParam Map<String, String> params,
            @RequestParam(defaultValue = "1") int currentPage,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestHeader("Authorization") String authorization) {
        try {
            // 提取 Token
            String token = authorization.replace("Bearer ", "");

// 解析 Token 获取当前用户ID（假设使用 JWT）
            JwtTokenUtil jwtTokenUtil = new JwtTokenUtil();
            String userId = jwtTokenUtil.getUserIdFromToken(token); // 自定义工具类解析Token

            // 创建 MyBatis Plus 的 Page 对象进行分页查询
            IPage<IntellectualProperty> page = new Page<>(currentPage, pageSize);
            QueryWrapper<IntellectualProperty> queryWrapper = new QueryWrapper<>();

// 强制添加当前用户ID条件
            // 强制添加当前用户ID条件：只显示包含当前用户ID的记录
            queryWrapper.apply("FIND_IN_SET({0}, user_id) > 0", userId);
//            queryWrapper.eq("user_id", userId);

            // 模糊查询条件 - 成果名称
            if (params.containsKey("nameKeyword") && params.get("nameKeyword") != null && !params.get("nameKeyword").isEmpty()) {
                queryWrapper.like("intellectual_achievement_name", params.get("nameKeyword"));
            }

            // 模糊查询条件 - 授权号
            if (params.containsKey("numberKeyword") && params.get("numberKeyword") != null && !params.get("numberKeyword").isEmpty()) {
                queryWrapper.like("authorization_number", params.get("numberKeyword"));
            }

            // 模糊查询条件 - 成果类别
            if (params.containsKey("categoryKeyword") && params.get("categoryKeyword") != null && !params.get("categoryKeyword").isEmpty()) {
                queryWrapper.like("intellectual_category", params.get("categoryKeyword"));
            }

            // 模糊查询条件 - 获得时间
            if (params.containsKey("intellectualYear") && params.get("intellectualYear") != null && !params.get("intellectualYear").isEmpty()) {
                queryWrapper.apply("YEAR(intellectual_year) = {0}", params.get("intellectualYear"));
            }

            // 精确查询条件 - 项目提交状态
            if (params.containsKey("intellectualStatus") && params.get("intellectualStatus") != null && !params.get("intellectualStatus").isEmpty()) {
                queryWrapper.eq("intellectual_status", params.get("intellectualStatus"));
            }

            // 精确查询条件 - 项目审核状态
            if (params.containsKey("intellectualReviewStatus") && params.get("intellectualReviewStatus") != null && !params.get("intellectualReviewStatus").isEmpty()) {
                queryWrapper.eq("intellectual_review_status", params.get("intellectualReviewStatus"));
            }

            // 调用 service 层的分页查询方法
            IPage<IntellectualProperty> resultPage = intellectualPropertyService.getIntellectualPropertyList(page, queryWrapper);

            // 构造返回结果
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "查询成功");
            response.put("data", resultPage.getRecords());
            response.put("total", resultPage.getTotal());
            response.put("currentPage", resultPage.getCurrent());
            response.put("pageSize", resultPage.getSize());
            response.put("totalPages", resultPage.getPages());

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "查询失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    /**
     * 新增决策咨询数据
     */
    @PostMapping("/addIntellectualPro")
    public ResponseEntity<Map<String, Object>> saveIntellectualPro(@RequestBody IntellectualProperty intellectualProperty,
                                                                   @RequestHeader("Authorization") String authorization) {
        System.out.println("前端数据：" + intellectualProperty);
        String token = authorization.replace("Bearer ", "");

// 解析 Token 获取当前用户ID（假设使用 JWT）
        JwtTokenUtil jwtTokenUtil = new JwtTokenUtil();
        String currentUserId = jwtTokenUtil.getUserIdFromToken(token); // 自定义工具类解析Token
        // 创建响应 Map
        Map<String, Object> response = new HashMap<>();
//        //1. 验证 username 是否存在
//        String usernameStr = intellectualProperty.getUsername();
//        if (usernameStr == null || usernameStr.trim().isEmpty()) {
//            response.put("code", 400);
//            response.put("msg", "用户名不能为空");
//            return ResponseEntity.badRequest().body(response);
//        }
//// 将用户名按逗号分隔
//        // 将中文逗号替换为英文逗号
//        String normalizedUsernameStr = usernameStr.replace("，", ",");
////        System.out.println("规范化后的用户名字符串：" + normalizedUsernameStr);
//
//        // 分割用户名
//        String[] usernameArray = normalizedUsernameStr.split(",");
////        System.out.println("分割后的用户名数组：" + Arrays.toString(usernameArray));
//        List<String> userIds = new ArrayList<>();
//        for (String username : usernameArray) {
//            System.out.println("username="+username);
//            String userId = userService.getUserIdByUsername(username.trim());
//            System.out.println("userid="+userId);
//            if (userId == null) {
//                response.put("code", 400);
//                response.put("msg", "用户不存在: " + username);
//                return ResponseEntity.badRequest().body(response);
//            }
//            userIds.add(userId);
//        }
//
//        // 校验当前用户是否在输入的用户ID列表中
//        if (!userIds.contains(currentUserId)) {
//            response.put("code", 403);
//            response.put("msg", "只能输入带有您的信息");
//            return ResponseEntity.status(HttpStatus.FORBIDDEN).body(response);
//        }

        // 1. 验证 username 是否存在
        String username = intellectualProperty.getUsername();
        if (username == null || username.isEmpty()) {
            response.put("code", 400);
            response.put("msg", "用户名不能为空");
            return ResponseEntity.badRequest().body(response);
        }

        // 2. 根据 username 查询 user_id
        String userId = userService.getUserIdByUsername(username);
        if (userId == null) {
            response.put("code", 400);
            response.put("msg", "用户不存在");
            return ResponseEntity.badRequest().body(response);
        }

        // 3. 设置 user_id 并保存
        intellectualProperty.setUserId(userId);

        // 1. 自动计算分值
        int baseScore = intellectualPropertyService.getScoreByType(intellectualProperty.getIntellectualCategory());
        intellectualProperty.setIntellectualScore(baseScore);
        // 2. 计算总分值
//        intellectualPropertyService.calculateTotalScore(intellectualProperty);

        // 设置状态为未提交
        intellectualProperty.setIntellectualStatus("未提交");
        intellectualProperty.setIntellectualReviewStatus("未审核");

        try {
//            System.out.println("intellectualProperty="+intellectualProperty);
            // 保存到数据库
            intellectualPropertyService.save(intellectualProperty);
            //总分值
            String year = null;

            if (intellectualProperty.getIntellectualYear() != null) {
                try {
                    // 支持 "yyyy-MM" 或 "yyyy/MM" 或 "yyyy" 格式
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
                    year = sdf.format(intellectualProperty.getIntellectualYear());
                } catch (Exception e) {
                    // 如果格式不对，兜底取前4位
                    year = intellectualProperty.getIntellectualYear().substring(0, 4);
                }
            }
            if (year != null) {
                intellectualPropertyService.updateTotalWorkIntellectualPropertyScore(userId, year);
            }

            // 返回成功响应
            response.put("code", 200);
            response.put("msg", "新增成功");
            return ResponseEntity.status(HttpStatus.CREATED).body(response);
        } catch (Exception e) {
            response.put("code", 500);
            response.put("msg", "服务器内部错误");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 修改决策咨询数据
     */
    @PutMapping("/updateIntellectualPro")
    public ResponseEntity<Map<String, Object>> updateIntellectualPro(
            @RequestBody IntellectualProperty intellectualProperty
    ) {
        // 1. 自动计算分值
        int baseScore = intellectualPropertyService.getScoreByType(intellectualProperty.getIntellectualCategory());
        intellectualProperty.setIntellectualScore(baseScore);

// 2. 计算总分值
//        intellectualPropertyService.calculateTotalScore(intellectualProperty);

        intellectualPropertyService.updateById(intellectualProperty);
        // 2. 计算总分值
        String year = null;
        if (intellectualProperty.getIntellectualYear() != null) {
            try {
                // 支持 "yyyy-MM" 或 "yyyy/MM" 或 "yyyy" 格式
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
                year = sdf.format(intellectualProperty.getIntellectualYear());
            } catch (Exception e) {
                // 如果格式不对，兜底取前4位
                year = intellectualProperty.getIntellectualYear().substring(0, 4);
            }
        }
        if (year != null) {
            intellectualPropertyService.updateTotalWorkIntellectualPropertyScore(intellectualProperty.getUserId(), year);
        }

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "修改成功");
        return ResponseEntity.ok(response);
    }

    /**
     * 删除数据
     */
    @DeleteMapping("/deleteUserIntelPro")
    public ResponseEntity<Map<String, Object>> deleteUserIntelPro(@RequestBody List<Long> ids) {
        // 1. 查出所有要删的数据
        List<IntellectualProperty> toDelete = intellectualPropertyService.listByIds(ids);

// 2. 记录所有受影响的 userId+year 组合
        Set<String> userYearSet = new HashSet<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        for (IntellectualProperty ip : toDelete) {
            if (ip.getUserId() != null && ip.getIntellectualYear() != null) {
                String year = null;
                try {
                    // 支持 "yyyy-MM" 或 "yyyy/MM" 或 "yyyy" 格式

                    year = sdf.format(ip.getIntellectualYear());
                } catch (Exception e) {
                    // 如果格式不对，兜底取前4位
                    year = ip.getIntellectualYear().substring(0, 4);
                }
                userYearSet.add(ip.getUserId() + "#" + year);
            }
        }

// 3. 删除
        intellectualPropertyService.removeByIds(ids);

// 4. 删除后，逐个更新 TotalWork
        for (String userYear : userYearSet) {
            String[] arr = userYear.split("#");
            String userId = arr[0];
            String year = arr[1];
            intellectualPropertyService.updateTotalWorkIntellectualPropertyScore(userId, year);
        }
        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "删除成功");
        return ResponseEntity.ok(response);
    }
    /**
     * 用户提交知识产权
     */
    @PostMapping("/submitIntellectualPro")
    public ResponseEntity<Map<String, Object>> submitIntellectualPro(@RequestBody Map<String, Object> params) {
        Map<String, Object> response = new HashMap<>();
        Long intellectualId = Long.valueOf(params.get("intellectualId").toString());
        IntellectualProperty property = intellectualPropertyService.getById(intellectualId);
        if (property == null) {
            response.put("code", 404);
            response.put("msg", "数据不存在");
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
        }
        property.setIntellectualStatus("已提交");
        property.setIntellectualReviewStatus("未审核");
        property.setIntellectualReviewTime(null);
        property.setIntellectualSubmissionTime(LocalDateTime.now());
        intellectualPropertyService.updateById(property);
        response.put("code", 200);
        response.put("msg", "提交成功");
        return ResponseEntity.ok(response);
    }

    /**
     * 用户撤回知识产权
     */
    @PostMapping("/revokeIntellectualPro")
    public ResponseEntity<Map<String, Object>> revokeIntellectualPro(@RequestBody Map<String, Object> params) {
        Map<String, Object> response = new HashMap<>();
        Long intellectualId = Long.valueOf(params.get("intellectualId").toString());
        IntellectualProperty property = intellectualPropertyService.getById(intellectualId);
        if (property == null) {
            response.put("code", 404);
            response.put("msg", "数据不存在");
            return ResponseEntity.ok(response);
        }
        // 只有审核通过/审核不通过不能撤回，其余都能撤回
        if ("审核通过".equals(property.getIntellectualReviewStatus()) || "审核不通过".equals(property.getIntellectualReviewStatus())) {
            response.put("code", 400);
            response.put("msg", "已审核，不可撤回");
            return ResponseEntity.ok(response);
        }
        property.setIntellectualStatus("未提交");
        property.setIntellectualSubmissionTime(null);
        property.setIntellectualReviewTime(null);
        intellectualPropertyService.updateById(property);
        response.put("code", 200);
        response.put("msg", "撤回成功");
        return ResponseEntity.ok(response);
    }

    @GetMapping("/export")
    public void exportIntellectualProperty(
            @RequestParam(value = "year", required = false) String year,
            @RequestHeader("Authorization") String authorization,
            HttpServletResponse response) throws Exception {
        // 1. 解析token获取userId
        String token = authorization.replace("Bearer ", "");
        JwtTokenUtil jwtTokenUtil = new JwtTokenUtil();
        String userId = jwtTokenUtil.getUserIdFromToken(token);

        // 2. 查找用户名
        User user = userService.getOne(new QueryWrapper<User>().eq("user_id", userId));
        String username = user != null ? user.getUsername() : "未知用户";

        // 3. 查询 IntellectualProperty（可按年份筛选）
        QueryWrapper<IntellectualProperty> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId); // 只查当前用户
        if (year != null && !year.isEmpty()) {
            queryWrapper.like("intellectual_year", year.substring(0, 4));
        }

        // 只导出审核通过的数据
//        queryWrapper.eq("intellectual_review_status", "审核通过");

        List<IntellectualProperty> list = intellectualPropertyService.list(queryWrapper);

        // 4. 查询所有用户，构建 userId -> username 映射
        List<User> userList = userService.list();
        Map<String, String> userIdNameMap = userList.stream()
                .collect(Collectors.toMap(User::getUserId, User::getUsername, (a, b) -> a));
        for (IntellectualProperty w : list) {
            w.setUsername(userIdNameMap.getOrDefault(w.getUserId(), ""));
        }

        // 5. 给每条数据加序号
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setRowNum(i + 1); // 从1开始
        }

        // 6. 生成文件名
        String now = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date());
        String fileName = "知识产权类-" + username + "-" + now + ".xlsx";
//        fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");

        // 7. 导出
        ExcelExportUtil.export(response, list, IntellectualProperty.class, "知识产权", fileName);
    }

}
